import resultful from "../api/resultful.js"; //返回数据构造

//执行SQL事务封装
export default class Exec {
  constructor(pool) {
    this.pool = pool;
  }

  /**
   * 执行SQL
   * sql 语句 select id form 表名 where id = ? and num = ?
   * then 回调函数
   * @description
   * 增加 INSERT INTO app_info VALUES (val1,val2,val3,val4)；
   * 删除 DELETE FROM app_info WHERE id=2；
   * 更新 UPDATE app_info SET id=2 WHERE name=小丽;
   * 查询 SELECT id FROM app_info limit 1;
   */
  query(sql, value = []) {
    return new Promise(async (resolve) => {
      const connection = await this.getConnection();
      connection.query(sql, value, (err, res, fields) => {
        console.log("执行sql=", sql);
        connection.release();
        if (err) {
          console.log("query err=", err);
          resolve(resultful("ERROR", err));
        } else {
          resolve(resultful("SUCCESS", res), fields);
        }
      });
    });
  }

  query1(sql, value = []) {
    return new Promise(async (resolve) => {
      const connection = await this.getConnection();
      connection.beginTransaction((error) => {
        if (error) {
          resolve(resultful("TransactionError", err));
          return;
        }
        connection.query(sql, value, (err, res, fields) => {
          console.log("执行sql=", sql);
          connection.release();
          if (err) {
            connection.rollback(() => {
              console.log("query err=", err);
              resolve(resultful("ERROR", err));
            });
            return;
          }
          connection.commit(() => {
            resolve(resultful("SUCCESS", res), fields);
          });
        });
      });
    });
  }

  getConnection() {
    return new Promise((resolve) => {
      this.pool.getConnection((error, conn) => {
        if (error) {
          console.log("conn err=", error);
          resolve(resultful("WARN"));
        } else {
          resolve(conn);
        }
      });
    });
  }
}
